import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'

const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    return config
  },
  (err) => Promise.reject(err)
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    if (res.data.code == 400) {
      // 处理业务失败, 给错误提示，抛出错误
      ElMessage.error(res.data.msg || '服务异常')
      return Promise.reject(res.data)
    }
    return res.data
  },
  (error) => {
    // 请求超时
    if (error.message.includes('timeout')) {
      // eslint-disable-next-line no-undef
      ElMessage({ type: 'error', message: '请求超时' })
      return Promise.reject(error)
    }

    // 未登录
    if (error.response?.status == 401) {
      // eslint-disable-next-line no-undef
      ElMessage.error('请先登录')
      const userStore = useUserStore()
      userStore.logout()
      let path = window.location.href.replace(window.location.origin, '')
      router.push(`/login?redirect=${path}`)
      return Promise.reject(new Error('未登录'))
    }
    // 系统异常
    // 需要和后端沟通错误响应的数据
    // eslint-disable-next-line no-undef
    ElMessage.error(error.response?.data.msg || '服务器异常')
    return Promise.reject(error)
  }
)

export default instance
